package org.jeecg.modules.demo.projectroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import liquibase.pro.packaged.L;
import org.jeecg.modules.demo.projectroom.entity.*;
import org.jeecg.modules.demo.projectroom.mapper.ZnzfProjectTypeMapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.jeecg.modules.demo.projectroom.entity.ZnzfProject;
import org.jeecg.modules.demo.projectroom.entity.ZnzfRoom;
import org.jeecg.modules.demo.projectroom.mapper.ZnzfRoomMapper;
import org.jeecg.modules.demo.projectroom.mapper.ZnzfProjectMapper;
import org.jeecg.modules.demo.projectroom.service.IZnzfProjectService;
import org.jeecg.modules.demo.projectroom.service.IZnzfRoomService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.*;

/**
 * @Description: 项目表
 * @Author: jeecg-boot
 * @Date:   2022-04-09
 * @Version: V1.0
 */
@Service
public class ZnzfProjectServiceImpl extends ServiceImpl<ZnzfProjectMapper, ZnzfProject> implements IZnzfProjectService {

	@Autowired
	private ZnzfProjectMapper znzfProjectMapper;
	@Autowired
	private ZnzfProjectTypeMapper znzfProjectTypeMapper;
	@Autowired
	private ZnzfRoomMapper znzfRoomMapper;
	@Autowired
	private IZnzfRoomService znzfRoomService;


	@Override
	@Transactional
	public void saveMain(ZnzfProject znzfProject, List<ZnzfRoom> znzfRoomList) {
		znzfProjectMapper.insert(znzfProject);
		if(znzfRoomList!=null && znzfRoomList.size()>0) {
			for(ZnzfRoom entity:znzfRoomList) {
				//外键设置
				entity.setProjectId(znzfProject.getId());
				znzfRoomMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(ZnzfProject znzfProject,List<ZnzfRoom> znzfRoomList) {
		znzfProjectMapper.updateById(znzfProject);
		
		//1.先删除子表数据
		znzfRoomMapper.deleteByMainId(znzfProject.getId());
		
		//2.子表数据重新插入
		if(znzfRoomList!=null && znzfRoomList.size()>0) {
			for(ZnzfRoom entity:znzfRoomList) {
				//外键设置
				entity.setProjectId(znzfProject.getId());
				znzfRoomMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void delMain(String id) {
		znzfRoomMapper.deleteByMainId(id);
		znzfProjectMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			znzfRoomMapper.deleteByMainId(id.toString());
			znzfProjectMapper.deleteById(id);
		}
	}


	/**
	 * 统计各站段房源情况
	 * @return
	 */
	@Override
	public Map<String, Integer> countRoomCntByStation() {
		Map<String, Integer> resMap = new HashMap<>();
		LambdaQueryWrapper<ZnzfProject> queryWrapper = new LambdaQueryWrapper<>();
		// 查询到一个站段下的项目列表（包括多个项目）
		List<ZnzfProject> projectList = znzfProjectMapper.selectList(queryWrapper);
		int sum = 0;
		// 统计这一站段下所有项目的全部房源数量
		/*for (int i = 0; i < projectList.size(); i++) {
			ZnzfProject project = projectList.get(i);
			// 获取项目id
			String id = project.getId();
			QueryWrapper<ZnzfRoom> roomQueryWrapper = new QueryWrapper<ZnzfRoom>();
			roomQueryWrapper.eq("project_id",id).select("COUNT(*) as roomCnt");
			Map<String, Object> map = znzfRoomService.getMap(roomQueryWrapper);
			Integer roomCnt = Integer. valueOf(String.valueOf(map.get("roomCnt")));
			sum += roomCnt.intValue();
		}*/
		for (int i = 0; i < projectList.size(); i++) {
			ZnzfProject project = projectList.get(i);
			String station = project.getStation();
			int roomNum = project.getRoomNum();
			if (resMap.containsKey(station)) {
				int tmp = resMap.get(station);
				int currRoomNum = tmp + roomNum;
				resMap.put(station, currRoomNum);
			} else {
				resMap.put(station, roomNum);
			}
		}
		return resMap;
	}

	/**
	 * 查询某个站段的房源具体情况（返回房间类型，状态，数量）
	 * @param station
	 * @return
	 */
	@Override
	public List<ZnzfStationParam> countRoomTypeCntByStation(String station) {
		// 返回列表
		List<ZnzfStationParam> resList = new LinkedList<ZnzfStationParam>();
		List<String> allStation = null;
		// 当station为空时得到所有站段的名字
		if (station == null) {
			allStation = getAllStation();
		}
		LambdaQueryWrapper<ZnzfProject> queryWrapper = new LambdaQueryWrapper<>();
		if (station != null) {
			queryWrapper.eq(ZnzfProject::getStation, station);
			ZnzfStationParam znzfStationParam = FindAllRoomParamOfStation(station);
			resList.add(znzfStationParam);
		} else {
			for (int i = 0; i < allStation.size(); i++) {
				String stationName = allStation.get(i);
				ZnzfStationParam znzfStationParam = FindAllRoomParamOfStation(stationName);
				resList.add(znzfStationParam);
			}
		}
		return resList;
	}

	@Override
	public List<ZnzfProject> searchsByCity(String city) {
		LambdaQueryWrapper<ZnzfProject> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(ZnzfProject::getCity, city);
		return znzfProjectMapper.selectList(queryWrapper);
	}

	/**
	 * 统计一个站段下各类房间的个数
	 * @param station 站段名称
	 * @return
	 */
	private ZnzfStationParam FindAllRoomParamOfStation(String station) {

		// 一个站段（station）的所有数据
		ZnzfStationParam znzfStationParam = new ZnzfStationParam();
		// 查询到一个站段下的项目列表（包括多个项目）
		LambdaQueryWrapper<ZnzfProject> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(ZnzfProject::getStation, station);
		List<ZnzfProject> projectList = znzfProjectMapper.selectList(queryWrapper);
		// 一个站段下的房间类型列表
		List<ZnzfRoomStateParam> znzfRoomStateParamList = new LinkedList<>();

		// 得到的各个房间类型的数目
		//Map<Integer, Long> roomStateNumMap = new HashMap<>();
		Map<ZnzfUniqueRoomType, Long> projectTypeMap = new HashMap<>();
		Integer currState = null;
		Long currNum = null;

		// 遍历一个站段下的所有项目（统计所有项目中各种状态房间的个数）
		for (int i = 0; i < projectList.size(); i++) {
			ZnzfProject project = projectList.get(i);
			// 查找房屋类型名称
			LambdaQueryWrapper<ZnzfProjectType> queryWrapper1 = new LambdaQueryWrapper<>();
			queryWrapper1.eq(ZnzfProjectType::getValue, project.getType());
			ZnzfProjectType znzfProjectType = znzfProjectTypeMapper.selectOne(queryWrapper1);

			String projectId = project.getId();
			// 统计一个项目下的同一个状态的
			QueryWrapper<ZnzfRoom> roomQueryWrapper = new QueryWrapper<ZnzfRoom>();
			roomQueryWrapper.select("state, count(*) AS num")
					.groupBy("state")
					.eq("project_id",projectId);
			List<Map<String, Object>> maps = znzfRoomMapper.selectMaps(roomQueryWrapper);

			for (int j = 0; j < maps.size(); j++) {

				ZnzfUniqueRoomType znzfUniqueRoomType = new ZnzfUniqueRoomType();
				Map<String, Object> map = maps.get(j);

				for (String key : map.keySet()) {
					if (key.equals("state")) {
						currState = (Integer) map.get(key);
						znzfUniqueRoomType.setState(currState);
					} else if (key.equals("num")) {
						currNum = (Long) map.get(key);
					}
				}
				znzfUniqueRoomType.setRoomType(znzfProjectType.getName());
				boolean containType = projectTypeMap.containsKey(znzfUniqueRoomType);
				if (containType) {
					Long lastNum = projectTypeMap.get(znzfUniqueRoomType);
					projectTypeMap.put(znzfUniqueRoomType, lastNum+currNum);
				} else {
					projectTypeMap.put(znzfUniqueRoomType, currNum);
				}
			}
		}

		Iterator<Map.Entry<ZnzfUniqueRoomType, Long>> entries = projectTypeMap.entrySet().iterator();
		while (entries.hasNext()) {
			// 一个项目下的一个房间类型（如公租房）
			ZnzfRoomStateParam znzfRoomStateParam = new ZnzfRoomStateParam();
			Map.Entry<ZnzfUniqueRoomType, Long> entry = entries.next();
			ZnzfUniqueRoomType uniqueRoomType = entry.getKey();
			Long num = entry.getValue();
			Integer state = uniqueRoomType.getState();
			String roomType = uniqueRoomType.getRoomType();
			// 设置房间各类状态的个数
			if (state == 0) {
				znzfRoomStateParam.setLiveNum(num.intValue());
			} else if (state == 1) {
				znzfRoomStateParam.setRepairNum(num.intValue());
			} else if (state == 2) {
				znzfRoomStateParam.setBlackNum(num.intValue());
			} else if (state == 3) {
				znzfRoomStateParam.setFramedNum(num.intValue());
			} else if (state == 4) {
				znzfRoomStateParam.setLockedNum(num.intValue());
			}
			znzfRoomStateParam.setType(roomType);
			// 添加一个房间类型
			znzfRoomStateParamList.add(znzfRoomStateParam);
		}

		znzfStationParam.setRoomStateParamList(znzfRoomStateParamList);
		znzfStationParam.setStation(station);
		return znzfStationParam;
	}


	/**
	 * 获取所有的站段名称
	 * @return
	 */
	private List<String> getAllStation() {
		List<String> allStationList = new LinkedList<>();
		// 找出所有的station(去重)
		QueryWrapper<ZnzfProject> stationWrapper = new QueryWrapper<>();
		stationWrapper.select("DISTINCT station");
		List<Map<String, Object>> maps = znzfProjectMapper.selectMaps(stationWrapper);
		maps.forEach(map->{
			Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();
			while (entries.hasNext()) {
				Map.Entry<String, Object> entry = entries.next();
				allStationList.add((String) entry.getValue());
			}
		});
		return allStationList;
	}


	@Override
	public int emptyTurnId(ZnzfProject znzfProject) {
		UpdateWrapper<ZnzfProject> updateWrapper = new UpdateWrapper<>();
		updateWrapper.set("turnId", null);
		updateWrapper.lambda().eq(ZnzfProject::getId, znzfProject.getId());
		return znzfProjectMapper.update(znzfProject,updateWrapper);
	}

}
